package com.neoCalf.neoCommon.utils;

import com.neoCalf.neoCommon.constants.Constants;
import com.neoCalf.neoCommon.enums.FileTypeEnum;
import com.neoCalf.neoCommon.enums.ResultCode;
import com.neoCalf.neoCommon.enums.UserContactTypeEnum;
import com.neoCalf.neoCommon.enums.ZeEnum;
import com.neoCalf.neoCommon.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.BindException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.neoCalf.neoCommon.constants.Constants.*;


@Slf4j
public class DataTool {
    private static final String STATIC_CHECK_CODE = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890";
    private static final int STR_LENGTH = STATIC_CHECK_CODE.length();

    public static void isNullThrow(Object... args) throws BindException {
        for (Object obj : args) {
            if (obj == null) {
                throw new BindException();
            }
        }
    }

    public static void checkAffectRow(int result) throws BusinessException {
        checkAffectRow(result, null);
    }

    public static void checkAffectRow(int result, String message) throws BusinessException {
        if (result == 0) {
            message = message.isEmpty() ? ResultCode.Fail.getMsg() : message;
            throw new BusinessException(ResultCode.Fail, message);
        }
    }

    public static void checkContactIdIsOwn(String userId, String contactId) {
        if (contactId.length() != 12 || userId.equals(contactId)) {
            throw new BusinessException(ResultCode.CODE_10017, "联系人ID错误");
        }
    }

    public static void checkUserFormat(String userId) throws Exception {
        if (!isStrLegal(userId) || userId.length() != 12) {
            throw new BindException("参数错误");
        }
    }

    public static boolean isNull(Object object) {
        return object == null;
    }

    public static boolean isStrLegal(String... args) {
        for (String str : args) {
            if (isNull(str) || str.isEmpty()) {
                return false;
            }
        }
        return true;
    }

    public static String getApplyInfo(UserContactTypeEnum type, String groupName, String nickName, String applyInfo) {
        if (applyInfo.isEmpty()) {
            switch (type) {
                case USER:
                    return Constants.APPLY_FRIEND_INFO.replace("U", nickName);
                case GROUP:
                    return Constants.APPLY_GROUP_INFO.replace("G", groupName) + "，" + Constants.APPLY_FRIEND_INFO.replace("U", nickName);
                default:
                    return applyInfo;
            }
        } else {
            if (type.equals(UserContactTypeEnum.GROUP)) {
                return Constants.APPLY_GROUP_INFO.replace("G", groupName) + "，" + applyInfo;
            }
            return applyInfo;
        }
    }

    public static boolean zeCheckStr(ZeEnum zeEnum, String str) {
        Pattern ze = Pattern.compile(zeEnum.getZe());
        Matcher matcher = ze.matcher(str);
        return matcher.matches();
    }

    public static boolean zeCheckStr(ZeEnum zeEnum, String[] strS) {
        for (String s : strS) {
            boolean b = zeCheckStr(zeEnum, s);
            if (!b) {
                return false;
            }
        }
        return true;
    }

    public static String buildCheckCode(int size) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
            int index = (int) (Math.random() * (STR_LENGTH));
            sb.append(STATIC_CHECK_CODE.charAt(index));
        }
        return sb.toString();
    }

    public static String buildKey(String email, String str) {
        return Md5Util.encodeByMd5(email).substring(6) + str;
    }

    public static String getUserId() {
        return UserContactTypeEnum.USER.getPrefix() + getRandomNumber(ID_LENGTH);
    }

    public static String getGroupId() {
        return UserContactTypeEnum.GROUP.getPrefix() + getRandomNumber(ID_LENGTH);
    }

    public static UserContactTypeEnum getContactTypeEnum(String contactId) {
        String prefix = contactId.substring(0, 1);
        UserContactTypeEnum typeEnum = UserContactTypeEnum.getByPrefix(prefix);
        if (typeEnum == null) throw new BusinessException(ResultCode.CODE_10017, "联系人ID错误");
        return typeEnum;
    }

    public static String getRandomNumber(Integer count) {
        return RandomStringUtils.random(count, false, true);
    }

    public static String getRandomString(Integer count) {
        return RandomStringUtils.random(count, true, true);
    }

    public static String cleanHtmlTag(String content) {
        if (content == null || content.isEmpty()) {
            return "";
        }
        return content.replace("<", "&1t;").replace("\r\n", "<br>").replace("\n", "<br>");
    }

    // 校验对象一致性 有抛错
    public static void checkIsOwner(String arg1, String arg2) throws Exception {
        if (!arg1.equals(arg2)) {
            throw new BindException();
        }
    }

    // 保存头像
    public static boolean saveAvatar(String dir, String path, String contactId, MultipartFile avatarFile, MultipartFile avatarCover) throws IOException {
        if (avatarFile != null && !avatarFile.isEmpty()) {
            File originDir = new File(dir + path + ORIGIN_IMAGE);
            File coverDir = new File(dir + path + COVER_IMAGE);
            boolean o = originDir.mkdirs();
            boolean c = coverDir.mkdirs();
            if (o && c) {
                log.info("新建目录{}", originDir.getParent());
                log.info("新建目录{}", coverDir.getParent());
            }
            File image = new File(originDir + "/" + contactId + PNG_SUFFIX);
            File imageCover = new File(coverDir + "/" + contactId + PNG_SUFFIX);
            avatarFile.transferTo(image);
            avatarCover.transferTo(imageCover);
            return true;
        }
        return false;
    }

    // 保存上传文件
    public static String saveUploadFile(String dir, String path, String userId, MultipartFile file, String fileName, FileTypeEnum fileType) throws IOException {
        String time = DateUtils.format(new Date(), "YYYY-mm-dd");
        File uploadDir = new File(dir + path);
        boolean o = uploadDir.mkdirs();
        if (o) {
            log.info("新建目录{}", uploadDir.getParent());
        }
        File uploadFile = new File(uploadDir + "/" + time + userId + fileName);
        file.transferTo(uploadFile);
        return uploadFile.getPath();
    }
}
